//表单信息的收集操作
/*
 name: '阿杰',
  tel: '18607440361',
  content: '项目名称：人才公寓管理平台，项目开发团队：如皋青软实训，项目开发进度：无，项目开发周期：无'
*/
const express = require('express')
const url=require('url')
const ClientModel=require('../modules/client.js');
const router = express.Router()

router.post('/contact/addsuccess',async(req,res)=>{
    // console.log(req.body);
    let{name,tel,content}=req.body;


    let ClientObj=new ClientModel({name,tel,content});
    ClientObj.save((error,data)=>{
        if(error){
            // console.log(error);
            res.send('add failure')
        }else{
            // console.log(data);
            let time=3;
            res.render('admin/success',{time})
        }
    });   
})
//项目信息的展示
router.get('/admin/client-list',async(req,res)=>{
    const infos=await ClientModel.find();
    // console.log(infos);
    res.render('admin/client-list',{infos});
})
//项目信息的删除
router.get('/admin/client-list/del',async(req,res)=>{
    // console.log(url.parse(req.url, true));
    // res.json(url.parse(req.url, true));
    let cateId=url.parse(req.url, true).query.id;
    try{
        await ClientModel.deleteOne({_id:cateId});
        res.redirect('back');
    }catch(e){
        res.redirect('back');
    }
})
//项目信息的编辑
router.get('/admin/client-list/edt',async(req,res)=>{
    let cateId=url.parse(req.url, true).query.id;
    let info=await ClientModel.findOne({_id:cateId});
    res.render('admin/client-edt',{info});
})

router.post('/admin/client/store',async(req,res)=>{
    let{name,tel,content,_id}=req.body;
    //根据当前的id，去查找记录然后在更新
    ClientModel.findById(_id,async(error,doc)=>{
        if(error){
            res.redirect('back');
        }else{
            doc.name=name;
            doc.tel=tel;
            doc.content=content;
            await doc.save();
            res.redirect('/admin/client-list');
        }
    })

   
})

module.exports = router;